package cn.edu.java.thread.锁;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static boolean flag = false;


    public static void main(String[] args) {
        Runnable printOdd = new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i += 2) {
                    lock.lock();
                    try {
                        while (!flag) {
                            condition.await();  // 线程等待，直到flag为true
                        }
                        System.out.println("奇数");
                        flag = false;
                        condition.signal();  // 通知其他等待线程
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };

        Runnable printEvent = new Runnable() {
            @Override
            public void run() {
                for (int i = 2; i <= 10; i += 2) {
                    lock.lock();
                    try {
                        while (flag) {
                            condition.await();  // 线程等待，直到flag为false
                        }
                        System.out.println("偶数");
                        flag = true;
                        condition.signal();  // 通知其他等待线程
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };


        new Thread(printEvent).start();
        new Thread(printOdd).start();


    }
}
